﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using AutoBuildVersion.Annotations;
using AutoBuildVersion.Helper;
using Button = System.Windows.Controls.Button;
using MessageBox = System.Windows.MessageBox;

namespace AutoBuildVersion
{
    /// <summary>
    ///     MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private static MainWindow _mainWindow;
        private string _assemblyTitle;
        private string _assemblyVersion;
        private bool _onlyCompileCore;
        private ObservableCollection<HistoryCompiledDir> _prePaths;
        private HistoryCompiledDir _selectPath;

        public MainWindow()
        {
            InitializeComponent();
            _mainWindow = this;
            DataContext = this;
        }

        /// <summary>
        ///     AssemblyVersion
        /// </summary>
        public string AssemblyVersion
        {
            set
            {
                _assemblyVersion = value;
                OnPropertyChanged("AssemblyVersion");
            }
            get { return _assemblyVersion; }
        }

        /// <summary>
        ///     AssemblyTitle
        /// </summary>
        public string AssemblyTitle
        {
            get { return _assemblyTitle; }
            set
            {
                _assemblyTitle = value;
                OnPropertyChanged("AssemblyTitle");
            }
        }

        /// <summary>
        ///     之编译core
        /// </summary>
        public bool OnlyCompileCore
        {
            get { return _onlyCompileCore; }
            set
            {
                _onlyCompileCore = value;
                OnPropertyChanged("OnlyCompileCore");
            }
        }

        /// <summary>
        ///     入口目录路径
        /// </summary>
        public string EntryPath
        {
            get
            {
                if (SelectPath == null)
                    return string.Empty;
                return SelectPath.Path;
            }
        }

        /// <summary>
        ///     历史编译
        /// </summary>
        public ObservableCollection<HistoryCompiledDir> PrePaths
        {
            get { return _prePaths; }
            set
            {
                _prePaths = value;
                OnPropertyChanged("PrePaths");
            }
        }

        public HistoryCompiledDir SelectPath
        {
            get { return _selectPath; }
            set
            {
                _selectPath = value;
                OnPropertyChanged("SelectPath");
                OnPropertyChanged("EntryPath");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void FillPrePaths()
        {
            PrePaths = new ObservableCollection<HistoryCompiledDir>();

            var filepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                           @"\ZilionCompilerHis\ZilionCompilerHis";
            if (!File.Exists(filepath))
                return;


            using (var sr = new StreamReader(filepath, Encoding.Default))
            {
                try
                {
                    string line;
                    while ((line = sr.ReadLine()).IsNotNullOrEmpty())
                    {
                        if (line.IsNotNullOrEmpty())
                        {
                            PrePaths.Add(new HistoryCompiledDir {Path = line});
                        }
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    sr.Close();
                }
            }

            if (PrePaths.Any())
                SelectPath = PrePaths.FirstOrDefault();
        }

        public static MainWindow GetWindow()
        {
            return _mainWindow ?? (_mainWindow = new MainWindow());
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (EntryPath.IsNullOrEmpty())
            {
                MessageBox.Show("请输入文件路径！");
                return;
            }


            //保存历史
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ZilionCompilerHis\";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            var filename = "ZilionCompilerHis";

            File.Delete(path + filename);
            using (var stream = new StreamWriter(path + filename, true, Encoding.Default))
            {
                try
                {
                    foreach (var info in PrePaths.Reverse())
                    {
                        stream.WriteLine(info.Path);
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    stream.Flush();
                    stream.Close();
                }
            }


            rtbStepDescription.Clear();
            rtbMainDescription.Clear();
            VersionChanger.ChangeVersion(EntryPath);

            //
            var root = new DirectoryInfo(EntryPath).Parent;
            if (root == null || !root.Exists)
            {
                MessageBox.Show("项目目录不存在！");
                return;
            }

            var compileCoreFiles = Directory.GetFiles(root.FullName).Where(x => x.EndsWith(@".sln")).ToList(); //获取项目根目录

            if (OnlyCompileCore)
            {
                if (compileCoreFiles.All(x => !x.Contains("ZilLion.Core.sln")))
                {
                    MessageBox.Show("ZilLion.Core.sln不存在无法编译！");
                    return;
                }
                MsBuilder.ReBulid("ZilLion.Core.sln", root.FullName);
            }
            else
            {
                var compileFilepath = compileCoreFiles.FirstOrDefault(x => !x.Contains("ZilLion.Core.sln"));
                if (compileFilepath.IsNullOrEmpty())
                {
                    var result = MessageBox.Show("项目目录不存在,是否编译Core？", "提示", MessageBoxButton.YesNo);
                    if (result == MessageBoxResult.Yes)
                    {
                        OnlyCompileCore = true;
                        MsBuilder.ReBulid("ZilLion.Core.sln", root.FullName);
                    }
                }
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            btnDisplayContent.IsChecked = true;
            FillPrePaths();
        }

        private void btnChooseDir_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new FolderBrowserDialog();
            dialog.ShowDialog();
            if (dialog.SelectedPath.IsNullOrEmpty()) return;
            var tmp = PrePaths.FirstOrDefault(x => x.Path == dialog.SelectedPath);

            if (tmp == null)
            {
                var compiledDir = new HistoryCompiledDir {Path = dialog.SelectedPath};
                PrePaths.Add(compiledDir);
                SelectPath = compiledDir;
            }
            else
            {
                SelectPath = tmp;
            }
        }

        private void rtbMainDescription_TextChanged(object sender, TextChangedEventArgs e)
        {
            rtbMainDescription.ScrollToEnd();
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            if (btn == null) return;
            var context = btn.DataContext as HistoryCompiledDir;
            if (context == null)
                return;
            PrePaths.Remove(context);
        }
    }

    public class HistoryCompiledDir : INotifyPropertyChanged
    {
        private DateTime _compileTime;
        private string _path;

        public string Path
        {
            get { return _path; }
            set
            {
                _path = value;
                OnPropertyChanged("Path");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}